const router = require('koa-router')()
const { resBody, aesDecrypt } = require('../../utils/index')
const { models, Sequelize } = require('../../utils/db');
const { Op, literal, col} = Sequelize;

// 用户登陆
router.post('/login', async(ctx, next) => {
    let {
        username = '',
        password = '',
        verificaCode = '',
    } = ctx.request.body;
    if (!username ||
        !password ||
        !verificaCode) {
            throw (resBody.paramError)
        }
    const sessionVerifyCode = ctx.session.verifyAdminCode;
    if (verificaCode.toLowerCase() !== sessionVerifyCode) {
        throw (resBody.verifyCodeErr)
    }
    let AdminInfo = await models.admin_model.findOne({
        where: {
            nickname: username,
        }
    });
    if (!AdminInfo) {
        throw (resBody.userNotVerified);
    }
    if (password !== aesDecrypt(AdminInfo.password)) {
        throw (resBody.passWordErr);
    }
    if (AdminInfo.password) {
        delete AdminInfo.password
    }
    ctx.session.login = true;
    ctx.session.adminInfo = AdminInfo;
    ctx.body = {
        ...resBody.success,
        msg: '登陆成功！',
        data: AdminInfo
    };
})

// 用户退出登陆
router.post('/loginOut', async(ctx, next) => {
    ctx.session = null;
    ctx.body = resBody.success;
})

// 获取用户信息
router.post('/getAdminInfo', async(ctx, next) => {
    const { login = false, adminInfo = {}} = ctx.session
    if (!login) {
        throw (resBody.notLoggedIn)
    } 
    ctx.body = {
        ...resBody.success,
        data: adminInfo
    };
})
// 获取句子列表
router.post('/getSentence', async(ctx) => {
    let { 
      pn = 1,
      ps = 10,
      id,
      categoryId,
      content,
      order
    } = ctx.request.body;
    let [ condition, count, data ] = [{}, 0, []];
    switch (order) {
      case 'rand':
        order = [[literal('RAND()')]];
        break;
      case 'asc':
        order = [['id', 'ASC']];
        break;
      case 'desc':
        order = [['id', 'DESC']];
        break;
      default:
        order = [['id', 'ASC']];
        break;
    }
    categoryId ? condition.categoryId = categoryId: '';
    id ? condition.id = id: '';
    content ? condition.content = {[Op.like]: `%${content}%`} : '';
    count = await models.sentence_model.count({where: condition});
    data = await models.sentence_model.findAll({
        raw: true,
        limit: ps,
        offset: (pn - 1) * ps,
        where: condition,
        order: order,
        attributes: ['id', 'categoryId', 'category', 'content', 'tag', 'tagId', 'like', 'collect']
    });
    ctx.body = {
      ...resBody.success,
      data: data,
      count
    }
});
// 获取句集列表
router.post('/getSpecial', async(ctx) => {
    let { 
        ps = 10,
        pn = 1,
        order,
        condition = {}
    } = ctx.request.body
    switch (order) {
        case 'rand':
            order = [[literal('RAND()')]];
            break;
        case 'asc':
            order = [['id', 'ASC']];
            break;
        case 'desc':
            order = [['id', 'DESC']];
            break;
        default:
            order = [['id', 'ASC']];
            break;
    }
    let data = await models.special_model.findAll({
        raw: true,
        where: condition,
        order: order,
        attributes: ['sid', 'title', 'categoryId'],
        limit: ps,
        offset: (pn - 1) * ps
    });
    let count = await models.special_model.count({
        where: condition
    });
    let maxPage = Math.ceil(count / ps)
    ctx.body = {
        ...resBody.success,
        data,
        count,
        maxPage
    };
});
module.exports = router
